package cn.net.autocode.platform.table;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.platform.table.ddl.DataBaseDDL;
import cn.net.autocode.platform.table.ddl.DatabaseDDLFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import cn.net.autocode.core.bean.ResultT;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController("platformTableFields")
@RequestMapping("/platform/tableFields")
public class TableFields {
    private final Dao dictDao;
    private final Dao dataDao;

    public TableFields(@Qualifier("dictDao") Dao dictDao, @Qualifier("dataDao") Dao dataDao) {
        this.dictDao = dictDao;
        this.dataDao = dataDao;
    }

    @RequestMapping("load")
    public ResultT load(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select * from ac_table_fields where table_id=? order by sort_no",param.getString("tableId"));
        return ResultT.success(array);
    }

    @RequestMapping("sort")
    public ResultT sort(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select * from ac_table_fields where table_id=? order by sort_no",param.getString("tableId"));
        for(int i=0;i<array.size();i++){
            JSONObject json = array.getJSONObject(i);
            int oldSortNo = json.getIntValue("sortNo");
            if (oldSortNo != i+1){
                json.put("sortNo",i+1);
                dictDao.executeUpdate("update ac_table_fields set sort_no=? where id=?",i+1,json.getString("id"));
            }
        }
        return ResultT.success(array);
    }

    @RequestMapping("change/{fieldName}")
    public ResultT change(@PathVariable("fieldName") String fieldName, @RequestBody JSONObject rowdata){
        switch(fieldName){
            case "remarks":
                dictDao.executeUpdate("update ac_table_fields set remarks=? where id=?",rowdata.getString("remarks"),rowdata.getString("id"));
                break;
            case "isnullable":
                dictDao.executeUpdate("update ac_table_fields set isnullable=? where id=?",rowdata.getString("isnullable"),rowdata.getString("id"));
                break;
            case "prohibitUpdate":
                dictDao.executeUpdate("update ac_table_fields set prohibit_Update=? where id=?",rowdata.getString("prohibitUpdate"),rowdata.getString("id"));
                break;
            case "defaultvalue":
                dictDao.executeUpdate("update ac_table_fields set defaultvalue=? where id=?",rowdata.getString("defaultvalue"),rowdata.getString("id"));
                break;
            case "sortNo":
                dictDao.executeUpdate("update ac_table_fields set sort_no=? where id=?",rowdata.getIntValue("sortNo"),rowdata.getString("id"));
                break;
        }
        return ResultT.success();
    }

    @RequestMapping("save")
    public ResultT save(@RequestBody JSONObject param){
        //数据处理
        param.put("name",param.getString("name").toLowerCase().trim());

        JSONObject tableJson = dictDao.queryJSON("select * from ac_table where id=?",param.getString("tableId"));
        String tableName = tableJson.getString("tableName");

        //判断新增还是修改
        String id = param.getString("id");
        if(StrUtil.isBlank(id)){
            //检查列是否存在
            int isExists = dictDao.queryValue("select count(*) from ac_table_fields where table_id=? and name=?",Integer.class,param.getString("tableId"),param.getString("name"));
            if(isExists>0){
                return ResultT.fail(param.getString("name")+"已经存在，不能重复添加");
            }

            //创建列
            DataBaseDDL ddl;
            try {
                ddl= DatabaseDDLFactory.newInstance(dataDao);
                ddl.addColumn(param,tableName);
            } catch (Exception e) {
                return ResultT.fail(e.getMessage());
            }

            //添加列信息
            int sortNo = dictDao.queryValue("select max(sort_no) from ac_table_fields where table_id=?",Integer.class,param.getString("tableId"));
            param.put("id", IdWorker.ulid());
            param.put("name",param.getString("name"));
            param.put("sortNo",sortNo+1);
            param.put("primaryKey","N");
            param.put("queryCriteria","eq");
            dictDao.createJSON(param,"ac_table_fields");
            dictDao.executeUpdate("update ac_table set is_sync='N' where id=?",param.getString("tableId"));
        }else{
            DataBaseDDL ddl;
            try {
                ddl=DatabaseDDLFactory.newInstance(dataDao);
                ddl.modifyColumn(param,tableName);
            } catch (Exception e) {
                return ResultT.fail(e.getMessage());
            }
            dictDao.updateJSON(param,"ac_table_fields");
            dictDao.executeUpdate("update ac_table set is_sync='N' where id=?",param.getString("tableId"));

        }
        return ResultT.success(param);
    }



    @RequestMapping("delete")
    public ResultT delete(@RequestBody JSONObject param){
        JSONObject tableJson = dictDao.queryJSON("select ac_table_fields.*,ac_table.table_name from ac_table_fields,ac_table where ac_table.id=ac_table_fields.table_id and ac_table_fields.id=?",param.getString("id"));
        String tableName = tableJson.getString("tableName");

        DataBaseDDL ddl;
        try {
            ddl=DatabaseDDLFactory.newInstance(dataDao);
            ddl.delColumn(tableJson.getString("name"),tableName);
        } catch (Exception e) {
            String message = e.getCause().getMessage();
            if(!message.contains("check that column/key exists")){
                return ResultT.fail(e.getMessage());
            }
        }

        dictDao.executeUpdate("delete from ac_table_fields where id=?",param.getString("id"));
        dictDao.executeUpdate("update ac_table set is_sync='N' where id=?",tableJson.getString("tableId"));
        //更新关联表
        dictDao.executeUpdate("update ac_table set is_sync='N' where exists(select 1 from ac_table_ref where ac_table.id=ac_table_ref.table_id and  fk_table=? and fk_field=? )",tableJson.getString("tableName"),tableJson.getString("name"));

        dictDao.executeUpdate("delete from ac_table_ref where fk_table=? and fk_field=?",tableJson.getString("tableName"),tableJson.getString("name"));
        //删除约束条件
        dictDao.executeUpdate("delete from ac_table_rules where table_id=? and field_name=? and rule_type<>32",tableJson.getString("tableId"),tableJson.getString("name"));

        JSONArray array = dictDao.queryJSONArray("select * from ac_table_rules where table_id=? and ref_column is not null and ref_column<>'[]'",tableJson.getString("tableId"));
        try {
            for(int i=0;i<array.size();i++){
                JSONObject rule = array.getJSONObject(i);
                String refColumn = rule.getString("refColumn");
                JSONArray refs = JSON.parseArray(refColumn);
                for(int j=0;j<refs.size();j++){
                    if(tableJson.getString("name").equals(refs.getString(j))){
                        dictDao.executeUpdate("delete from ac_table_rules where id=?",rule.getString("id"));
                    }
                }
            }
        } catch (Exception ignored) {

        }
        return ResultT.success();
    }
}
